<template>
	<view class="qrcodeModel">
		<!-- 展示二维码弹框 -->
		<up-modal
			width="488rpx"
			:closeOnClickOverlay="true"
			:show="showPopup"
			:showConfirmButton="false"
			class="contact_model"
			styleIsolation="shared"
			@close="closePopup"
		>
			<image class="bg" src="/static/imgs/home/qr_bg.png" />
			<view class="contact_model_box">
				<view class="qrcode">
					<image :src="qrcodeUrl" mode=""></image>
				</view>
				<myButton
					bgcColor="#F3E0BB"
					name="保存到相册"
					width="296rpx"
					@clickBtn="handleSave"
				>
					<image
						src="http://112.124.50.179:8888/imgs/service/download.png"
						mode=""
						style="width: 28rpx; height: 28rpx; margin-right: 8rpx"
					></image>
				</myButton>
			</view>
		</up-modal>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive, watch } from 'vue';
// #ifdef H5
import { saveAs } from 'file-saver';
// #endif
import myButton from '../button/index.vue';
import _ from 'lodash';

const props = defineProps({
	show: {
		type: Boolean,
		required: true,
		default: false
	},
	qrcodeUrl: {
		type: String,
		required: true
	}
});
const emits = defineEmits('update:show');
const showPopup = ref(false);

watch(
	() => props.show,
	(newValue) => {
		showPopup.value = newValue;
	}
);

//微信小程序上支持类型穿透
defineOptions({
	options: {
		styleIsolation: 'shared'
	}
});

const closePopup = () => {
	showPopup.value = false;
	emits('update:show', false);
};

const handleSave = _.debounce(
	function () {
		// #ifdef H5
		saveImg();
		// #endif

		// #ifdef MP-WEIXIN || APP
		saveInAlbum();
		// #endif
	},
	2000,
	{
		leading: true,
		trailing: false
	}
);

const saveInAlbum = () => {
	const url = props.qrcodeUrl; // 真正要下载的图片地址
	let filename = '客服二维码-' + new Date().getTime() + '.jpg';
	let filePath = wx.env.USER_DATA_PATH + '/' + filename; // wx.env.USER_DATA_PATH：获取到这个目录的路径。
	console.log('图片临时地址', filePath);
	uni.authorize({
		scope: 'scope.writePhotosAlbum',
		success() {
			uni.showLoading({ title: '图片保存中', mask: true });
			uni.downloadFile({
				url: url,
				filePath: filePath,
				fail(err) {
					uni.hideLoading();
					console.error('保存失败，错误信息：', err);
					uni.showToast({
						title: '保存失败，请稍后重试',
						icon: 'none'
					});
				},
				success(res) {
					uni.saveImageToPhotosAlbum({
						filePath: res.filePath,
						success() {
							uni.hideLoading();
							uni.showToast({
								title: '保存成功，可到相册中查看',
								icon: 'none'
							});
							// 删除缓存
							let fileMgr = wx.getFileSystemManager();
							fileMgr.unlink({
								filePath: filePath, // 这里是上面自己设置的临时文件路径
								success() {
									console.log('删除成功');
								},
								fail(err) {
									console.error('删除失败，错误信息：', err);
								}
							});
						},
						fail(err) {
							uni.hideLoading();
							console.error('保存失败，错误信息：', err);
							uni.showToast({
								title: '保存失败，请稍后重试',
								icon: 'none'
							});
						}
					});

					console.log(res);
				}
			});
		},
		fail: (fail) => {
			uni.hideLoading();
			console.log('授权失败：', fail);
		}
	});
};

/**
 * 保存在相册
 */
const saveImg = () => {
	//跨域问题：https://blog.csdn.net/ManNiaoQinFen/article/details/131740796
	uni.downloadFile({
		//下载
		url: props.qrcodeUrl, //图片下载地址
		success: (res) => {
			console.log(res);
			if (res.statusCode === 200 || res.statusCode === 400) {
				/**
				 *保存文件到本地
				 *res.tempFilePath：下载好文件的临时路径，用来保存
				 *this.uploadedFile.name：下载的文件名称
				 */
				saveAs(res.tempFilePath, '客服二维码');
			}
		}
	});
};
</script>
<style lang="scss">
.bg {
	width: 590rpx;
	height: 740rpx;
	position: fixed;
	z-index: -1;
	border-radius: 0% !important;
}

/* #ifdef MP-WEIXIN */
.qrcodeModel {
	::v-deep .u-popup__content {
		background: none !important;
	}

	::v-deep .u-modal__content {
		padding: 0 !important;
	}

	::v-deep .u-line {
		display: none !important;
	}
}

/* #endif */

.contact_model {
	::v-deep .u-popup__content {
		background: none !important;
	}

	::v-deep .u-modal__content {
		padding: 0 !important;
	}

	::v-deep .u-line {
		display: none !important;
	}
}

.contact_model_box {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	margin-top: 208rpx;

	.qrcode {
		width: 334rpx;
		height: 334rpx;
		margin-bottom: 52rpx;

		image {
			width: 100%;
			height: 100%;
			border-radius: 0% !important;
		}
	}
}
</style>
